﻿using Microsoft.EntityFrameworkCore;
using S.Weaning.Domain;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace S.Weaning.Infrastructure
{

    public class BaseRepository<T> : IBaseRepository<T> where T : class
    {
        private readonly MyDbContext db;

        public BaseRepository(MyDbContext db)
        {
            this.db = db;
        }
        public bool Add(T t)
        {
            db.Set<T>().Add(t);
            return db.SaveChanges() > 0;
        }

        public async Task<bool> AddAsync(T t)
        {
            db.Set<T>().Add(t);
            return await db.SaveChangesAsync() > 0;
        }

        public bool Delete(int id)
        {
            var a = db.Set<T>().Find(id);
            db.Set<T>().Remove(a);
            return db.SaveChanges() > 0;
        }

        public async Task<bool> DeleteAsync(int id)
        {
            var a = db.Set<T>().Find(id);
            db.Set<T>().Remove(a);
            return await db.SaveChangesAsync() > 0;
        }

        public IQueryable<T> GetAll()
        {
            return db.Set<T>().AsQueryable();
        }

        public async Task<List<T>> GetAllAsync()
        {
            return await db.Set<T>().ToListAsync();
        }

        public bool Update(T t)
        {
            db.Set<T>().Update(t);
            return db.SaveChanges() > 0;
        }

        public async Task<bool> UpdateAsync(T t)
        {
            db.Set<T>().UpdateRange(t);
            return await db.SaveChangesAsync() > 0;
        }
    }
}
